//
//  NoticeViewController.m
//  Contacts
//
//  Created by 李 雷川 on 14-7-15.
//  Copyright (c) 2014年 李 雷川. All rights reserved.
//

#import "NoticeViewController.h"
#import "CategoryCell.h"
#import "NoticeCategory.h"
#import "NoticeCategoryDao.h"
#import "ServerInterface.h"
#import "Contact.h"
#import "NoticeListViewController.h"
#import "MLPAccessoryBadge.h"
#import "UIColor+MLPFlatColors.h"
extern Contact *globalContact;
@interface NoticeViewController (){
    NSArray *categorys;
    IBOutlet UITableView *categoryTableView;
}

@end

@implementation NoticeViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.title = @"通知";
    categorys = [NoticeCategory getCategorys];
    NSDictionary *paramDic = @{@"company_id":CompanyID,@"token":globalContact.token,@"user_id":@(globalContact.userID)};
    [ServerInterface getCategoryWithDic:paramDic withBlock:^(NSDictionary *newDic, NSError *error) {
        //NSLog(@"news is:%@",newDic);
        if (error) {
            //NSLog(@"error is:%@",error);
        }
        else{
            if ([[newDic valueForKeyPath:@"success"] boolValue]) {
                NSArray *newArr = newDic[@"data"];
                NSMutableArray *arr = [NSMutableArray arrayWithCapacity:newArr.count];
                for (NSDictionary *categoryDic in newArr) {
                    NoticeCategory *category = [NoticeCategory analysisNoticeCategoryWithDic:categoryDic];
                    [arr addObject:category];
                }
                categorys = [NSArray arrayWithArray:arr];
                [NoticeCategory saveWithCategorys:categorys];
                [self.tableView reloadData];
            }
            else{
                
            }
        }
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return categorys.count%2 == 0?(categorys.count/2):(categorys.count/2 + 1);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count = 2;
    (section +1) * 2 > categorys.count ?(count =1):(count = 2);
    return count;
}


- (CategoryCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CategoryCell" forIndexPath:indexPath];
    
    if (!cell) {
        cell = [[CategoryCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CategoryCell"];
    }
    NoticeCategory *category = categorys[indexPath.section * 2 + indexPath.row];
    cell.titleLabel.text = category.name;
    [cell.logoImageView setImageWithURL:[NSURL URLWithString:category.imageIco] placeholderImage:
                           [UIImage imageNamed:@""]];
    __weak CategoryCell *categoryCell = cell;
    NSString *filePath =[IMAGE_FORDER stringByAppendingPathComponent:[category.imageIco lastPathComponent]];
    if ([filePath hasSuffix:@"png"] || [filePath hasSuffix:@"jpg"]) {
        if ([[NSFileManager defaultManager]fileExistsAtPath:filePath isDirectory:nil]) {
            categoryCell.logoImageView.image = [UIImage imageWithContentsOfFile:filePath];
        }
        else{
            [categoryCell.logoImageView setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:category.imageIco]]  placeholderImage: [UIImage imageNamed:@""]  success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                categoryCell.logoImageView.image = image;
                
                if (![[NSFileManager defaultManager] fileExistsAtPath:IMAGE_FORDER isDirectory:nil]) {
                    [[NSFileManager defaultManager]createDirectoryAtPath:IMAGE_FORDER withIntermediateDirectories:YES attributes:nil error:nil];
                }
                BOOL success = [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
                if (success) {
                    
                }
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
            }];

        }
    }
    
//    MLPAccessoryBadgeArrow  *accessoryBadge = [MLPAccessoryBadgeArrow new];
//    [cell setAccessoryView:accessoryBadge];
//    [accessoryBadge setTextWithNumber:@(category.newsCount)];
//    [accessoryBadge setBackgroundColor:[UIColor flatRedColor]];
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
     [categoryTableView deselectRowAtIndexPath:indexPath animated:YES];
    NoticeListViewController *viewController = segue.destinationViewController;
      NoticeCategory *category = categorys[indexPath.section *2 + indexPath.row];
    [viewController initWithCategory:category];
}

@end
